<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>

</body>
<script>

  function getUrlParams(url = location.href) {
    const Params = {}
    if (url.indexOf('?') > 0) {//判断是否有qurey
      let parmas = url.slice(url.indexOf('?') + 1)//截取出query
      const paramlists = parmas.split('&')//分割键值对
      for (const param of paramlists) {
        let a = param.split('=')
        Object.assign(Params, { [a[0]]: a[1] })//将键值对封装成对象
      }
    }
    return Params
  }
  const options = getUrlParams()

  if (options.code) {
    //微信跳入中转页
    let originUrl = decodeURIComponent(localStorage.getItem('originUrl'))
    //把code放到参数最前面
    if (originUrl.includes('?')) {
      let reg = originUrl.includes('&') ? /(?<=\?).*(?=\&)/ : /(?<=\?).*/
      originUrl = originUrl.replace(reg, val => `code=${options.code}&${val}`)
    } else {
      originUrl += `?code=${options.code}`
    }
    window.location.href = originUrl
  } else {
    // 用户跳入中转页
    if (options.redirect_uri) {
      localStorage.setItem('originUrl', options.redirect_uri)
    }
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${options.appid}&redirect_uri=${encodeURIComponent('http://hzy45.gitee.io/h5-bridge')}&response_type=code&scope=${options.scope}&state=STATE#wechat_redirect`
  }
</script>

</html>